/*
 * @Author: error: error: git config user.name & please set dead value or install git && error: git config user.email & please set dead value or install git & please set dead value or install git
 * @Date: 2025-03-12 21:24:31
 * @LastEditors: error: error: git config user.name & please set dead value or install git && error: git config user.email & please set dead value or install git & please set dead value or install git
 * @LastEditTime: 2025-03-12 22:12:07
 * @FilePath: /lesson/Thread_mutex_cond/test_cond/test_cond.cc
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
#include<iostream>
#include<string>
#include<pthread.h>
#include<unistd.h>
using namespace std;

const static int num=2;

pthread_mutex_t gmutex=PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t gcond = PTHREAD_COND_INITIALIZER;

void* Routine_Print(void* args)
{
    string name=static_cast<const char*> (args);
    while(true)
    {
        pthread_mutex_lock(&gmutex);

        pthread_cond_wait(&gcond,&gmutex);// 线程在这里等待~

        cout<<" 我是 : "<<name<<endl;

        pthread_mutex_unlock(&gmutex);
        sleep(1);
    }
}

int main()
{
    pthread_t threads[num];
    for(int i=0;i<num;i++)
    {
        char* name=new char[1024];//这个name是我们给每一个线程起的名字，需要单独开辟一个空间然后传递给每个线程，

        snprintf(name,1024,"thread - %c",'A'+ i); // 这样能理解吗? 可以
        pthread_create(threads+i,nullptr,Routine_Print,(void*)name);
        usleep(10000);
    }

    sleep(1);
    
    // 唤醒其他线程
    while(true)
    {
        pthread_cond_broadcast(&gcond);
        cout<< " 唤醒所有线程..."<<endl;
        sleep(1);
    }

    // 等待所有线程
    for(int i=0;i<num;i++)
    {
        pthread_join(threads[i],nullptr);
    }
    return 0;
}